import { Toast } from 'qmp-component'
import { reactive, computed } from 'vue'
import { SimpleEvents } from '@/utils'
import { saveHandover } from '@/apis/ctmCustomerChange/index'
import { getAttachmentTemplate, queryAttachmentList } from '@/apis/common'
interface anyObjectModle {
  [key: string]: any
}

/**
 * 交接情况编辑
 */
export function createHandoverMixin(instanceName: string, $router: any, detailFunc: Function, callback: Function) {
  const datas = reactive<anyObjectModle>({
    id: '',
    detail: {},
    isMarketConnect: '', // 是否交接
    isTakeOverTheOriginalStore: '', //是否接管原商家门店(仅用于经销商档案新建)
    isHandoverDistribution: '', // 是否交接分销客户
    list: [],
    attachment: {
      relativeFiles: [], // 关系证明
      handoverFiles: [], // 交接证明
      handoverSiteFiles: [] //交接现场照片
    },
    templateFileList: {
      ACCESS111: [] //交接双方现场签订照片模板下载
    }
  })

  let editRowIndex = 0 // 当前编辑项(跳转页面需要记录)

  const defaultData = {
    fromCustomerCode: '', // 原商家客户编码
    fromCustomerName: '', //原商家客户名称
    fromAccountCode: '',
    fromAccountName: '', // 原业务账号
    toAccountCode: '',
    toAccountName: '', // 现业务账号
    fromShopCode: '',
    fromShopName: '', // 原门店

    relationCode: '',
    relationName: '', // 新老商家关系
    afterServiceAccount: '',
    afterServiceAccountName: '', // 售后负责人
    reason: '',
    isTransferSales: false,
    rebatepRoblem: '',
    rebatepRoblemName: '', // 返利对象
    isContinuePromotion: false,
    isTransferBalance: false,
    isTransferDeposit: false
  }
  const getDetail = () => {
    const id = `${datas.id}`
    detailFunc(id).then((res: any) => {
      const d = res.data
      datas.detail = d
      datas.isMarketConnect = ['1', 1, '0', 0].includes(d.isMarketConnect) ? Number(d.isMarketConnect) : ''
      datas.isTakeOverTheOriginalStore = ['1', 1].includes(d.isTakeOverTheOriginalStore)
        ? '1'
        : ['0', 0].includes(d.isTakeOverTheOriginalStore)
        ? '0'
        : ''
      datas.list = d?.handoverDTOS || []
      /* datas.isHandoverDistribution = datas.list.some((e: any) => [1, '1'].includes(e.isHandoverDistribution))
        ? '1'
        : '0' */
      datas.isHandoverDistribution = d.isHandoverDistribution
      handleMarketConnect(datas.isMarketConnect, true)
    })
  }
  const onCreat = () => {
    const obj: any = { ...defaultData, ...{ code: 'TS' + new Date().getTime() } }
    datas.list.push(obj)
  }

  const onDelete = (i: number) => {
    datas.list.splice(i, 1)
  }

  const onSave = () => {
    const { list, attachment, isHandoverDistribution } = datas
    let { isTakeOverTheOriginalStore } = datas
    let handoverDTOS = []
    let attachmentTypeCodes = []
    const isMarketConnect = [1, '1'].includes(datas.isMarketConnect) ? 1 : 0
    if (!isMarketConnect) isTakeOverTheOriginalStore = 0
    if (![1, '1', '0', 0].includes(isTakeOverTheOriginalStore)) {
      Toast('请选择是否接管原商家门店')
      return
    }
    if ([1, '1'].includes(isMarketConnect)) {
      if (list.length === 0) {
        Toast('请添加交接业务账号')
        return
      }
      if (
        hasIsTransferSales.value &&
        (attachment.relativeFiles.length === 0 ||
          attachment.handoverFiles.length === 0 ||
          attachment.handoverSiteFiles.length === 0)
      ) {
        Toast('附件必须上传')
        return
      }
    }
    handoverDTOS = isMarketConnect
      ? list.map((e: any) => {
          return { ...e, ...{ changeCode: datas.detail.code } }
        })
      : []
    if (instanceName === 'DealerNewArchiveHandover') {
      // 新建档案
      attachmentTypeCodes = ['ACCESS058', 'ACCESS059', 'ACCESS111']
      /* handoverDTOS = list.map((e: any) => {
        return { ...e, ...{ isHandoverDistribution, changeCode: datas.detail.code } }
      }) */
    } else {
      // 新建门店
      attachmentTypeCodes = isMarketConnect ? ['ACCESS063', 'ACCESS064', 'ACCESS111'] : []
    }

    const data: anyObjectModle = {
      changeCode: datas.detail.code,
      isMarketConnect,
      isTakeOverTheOriginalStore,
      attachmentDTOS: [...attachment.relativeFiles, ...attachment.handoverFiles, ...attachment.handoverSiteFiles],
      attachmentTypeCodes,
      handoverDTOS
    }

    if (instanceName === 'DealerNewArchiveHandover') {
      data.isHandoverDistribution = [1, '1'].includes(isHandoverDistribution) ? 1 : 0
    }

    saveHandover(data).then((res: any) => {
      if (res.success === 1) {
        Toast('保存成功')
        callback && callback()
      }
    })
  }
  // 监听商家客户信息选择
  SimpleEvents.registerEvent(`${instanceName}_setSelectedBusinessCustomer`, (d: any) => {
    const list = datas.list.map((v: any, i: number) => {
      const tmp = { ...v }
      if (editRowIndex === i) {
        tmp.fromCustomerCode = d.code
        tmp.fromCustomerName = d.name
      }
      return tmp
    })
    datas.list = list
  })
  // 监听业务账号选择
  SimpleEvents.registerEvent(`${instanceName}_setSelectedAccount`, (d: any) => {
    const list = datas.list.map((v: any, i: number) => {
      const tmp = { ...v }
      if (editRowIndex === i) {
        tmp.fromAccountCode = d.code
        tmp.fromAccountName = d.name
      }
      return tmp
    })
    datas.list = list
  })

  // 监听门店选择
  SimpleEvents.registerEvent(`${instanceName}_setSelectedShop`, (d: any) => {
    const list = datas.list.map((v: any, i: number) => {
      const tmp = { ...v }
      if (editRowIndex === i) {
        tmp.fromShopCode = d.code
        tmp.fromShopName = d.name
      }
      return tmp
    })
    datas.list = list
  })

  const onSearchAccount = (i: number, customerCode?: string) => {
    // console.log('customerCode', customerCode)
    editRowIndex = i
    $router.push({
      path: '/search/account',
      query: {
        office: datas.detail.officeCode,
        name: `${instanceName}_setSelectedAccount`,
        customer: customerCode
      }
    })
  }

  const onSearchShop = (i: number) => {
    editRowIndex = i
    $router.push({
      path: '/search/shop',
      query: {
        office: datas.detail.officeCode,
        name: `${instanceName}_setSelectedShop`
      }
    })
  }

  const onSearchCustomer = (i: number) => {
    editRowIndex = i
    $router.push({
      path: '/search/businessCustomer',
      query: {
        office: datas.detail.officeCode,
        name: `${instanceName}_setSelectedBusinessCustomer`
      }
    })
  }

  const handleMarketConnect = (data: boolean, flag?: boolean) => {
    // 是否经销商交接值为是时，默认显示一条交接账号信息
    if (!data) {
      datas.isTakeOverTheOriginalStore = 0
    } else {
      if (flag !== true) {
        datas.isTakeOverTheOriginalStore = ''
      }
    }
    if (data && !datas.list.length) {
      onCreat()
    }
  }
  // 是否转让为否时，不需要上传经销商关系证明附件与交接现场照片
  const hasIsTransferSales = computed(() => {
    return datas.list.some((v: any) => Number(v.isTransferSales) === 1)
  })

  const downTemplate = async () => {
    const codes = ['ACCESS111'] // 需下载模板的附件类型编码
    codes.forEach(async (code) => {
      const configId = await getAttachmentTemplate(code)
      if (configId) {
        const data = await queryAttachmentList(configId)
        datas.templateFileList[code] = data
      }
    })
  }

  return {
    datas,
    getDetail,
    onCreat,
    onDelete,
    onSave,
    onSearchAccount,
    onSearchShop,
    onSearchCustomer,
    handleMarketConnect,
    hasIsTransferSales,
    downTemplate
  }
}
